<template>
  <div class="app-container">
    <el-card class="box-card">
      <h3>充值信息</h3>
      <el-form
        ref="charge"
        :rules="rules"
        :model="charge"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 800px; margin-left:50px;"
      >
        <el-form-item label="所属企业">
          <el-select v-model="charge.companyId" clearable>
            <el-option v-for="item in companyList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="充值金额" prop="chargeMoney">
          <el-input v-model="charge.chargeMoney" type="number" />
        </el-form-item>

      </el-form>
    </el-card>

    <el-card class="box-card">
      <h3>兑换券信息</h3>
      <el-row :gutter="20" type="flex" align="middle" style="padding:20px 0;">
        <el-col :span="10">
          <el-button :plain="true" type="primary" @click="handleCdkeyShow">添加</el-button>
        </el-col>
      </el-row>

      <el-table :data="cdkeys">
        <el-table-column property="faceValue" label="面值" />
        <el-table-column property="number" label="数量" />
        <el-table-column
          align="center"
          label="操作"
          width="250"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="handleCdkeyDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog :visible.sync="cdkeyVisiable" title="设置兑换码">
        <el-form
          ref="cdkeyForm"
          :rules="rules"
          :model="cdkeyForm"
          status-icon
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item label="面额" prop="faceValue">
            <el-input v-model="cdkeyForm.faceValue" type="number" />
          </el-form-item>
          <el-form-item label="数量" prop="number">
            <el-input v-model="cdkeyForm.number" type="number" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cdkeyVisiable = false">取消</el-button>
          <el-button type="primary" @click="handleCdkeyAdd">确定</el-button>
        </div>
      </el-dialog>
    </el-card>
    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm">保存</el-button>
    </div>
  </div>
</template>

<style>
  .el-card {
    margin-bottom: 10px;
  }
</style>
<script>
import { createCharge } from '@/api/charge'
import { listCompany } from '@/api/company'
import { getToken } from '@/utils/auth'

export default {
  name: 'ChargeEdit',
  data() {
    return {
      id: 0,
      charge: {},
      companyList: [],
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 5,
        id: undefined,
        name: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      cdkeys: [],
      cdkeyForm: { faceValue: '', number: '' },
      cdkeyVisiable: false,
      rules: {
        chargeMoney: [
          { required: true, message: '充值金额不能为空', trigger: 'blur' }
        ],
        companyId: [
          { required: true, message: '企业不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init: function() {
      this.listLoading = true
      listCompany(this.listQuery).then(response => {
        this.companyList = response.data.data.list
        this.listLoading = false
      }).catch(() => {
        this.companyList = []
        this.listLoading = false
      })
    },
    validFaceValue: function() {
      let message = ''
      if (this.charge.chargeMoney > 0) {
        const money = this.cdkeys.map((item, index, arr) => {
          return item.number * item.faceValue
        })
        const sum = money.reduce((prev, cur, item, arr) => {
          return prev + cur
        })
        if ('' + sum !== this.charge.chargeMoney) {
          message = '充值面额' + this.charge.chargeMoney + '和兑换码总价值' + sum + '不相等'
        }
      } else {
        message = '充值面额应大于0'
      }
      return message
    },
    handleCreate() {

    },

    handleCancel() {
      this.$router.push({ path: '/company/charge' })
    },
    handleConfirm() {
      this.$refs['charge'].validate(valid => {
        const finalCharge = {
          charge: this.charge,
          cdkeys: this.cdkeys
        }
        if (valid) {
          const message = this.validFaceValue()
          if (message === '') {
            createCharge(finalCharge).then(response => {
              this.$router.push({ path: '/company/charge' })
            })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          } else {
            this.$notify.error({
              title: '失败',
              message: message
            })
          }
        }
      })
    },

    handleCdkeyShow() {
      this.cdkeyForm = { faceValue: '', number: '' }
      this.cdkeyVisiable = true
    },
    handleCdkeyAdd() {
      var index = this.cdkeys.length - 1
      for (var i = 0; i < this.cdkeys.length; i++) {
        const v = this.cdkeys[i]
        if (v.faceValue === this.cdkeyForm.faceValue) {
          this.$message({
            type: 'warning',
            message: '已经存在面值:' + v.faceValue
          })
          this.cdkeyForm = {}
          this.cdkeyVisiable = false
          return
        } else {
          index = i
        }
      }

      this.cdkeys.splice(index + 1, 0, this.cdkeyForm)
      this.cdkeyVisiable = false
    },
    handleCdkeyDelete(row) {
      const index = this.cdkeys.indexOf(row)
      this.cdkeys.splice(index, 1)
    }
  }
}
</script>
